package com.feng.util.xml;


import java.util.HashMap;
import java.util.Map;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**
 * 通过SAX 解析xml方式由xml生成java的Map对象的Handler类  
 * @author Administrator
 *
 */
public class MapSAXHandler extends DefaultHandler{
	
	private String mCurrentTAG;
	private Map<String, String> data;	
	public MapSAXHandler(){
		data = new HashMap<String, String>();
	}
	
	public Map<String, String> getParseData(){
		return data;
	}
	
	@Override
	public void startElement(String uri, String localName, String name,
			Attributes attr) throws SAXException {
		mCurrentTAG = name;
		int len = attr.getLength();
		for(int i=0;i<len;i++){
			System.out.println(String.format("attr(%s) value(%s)", attr.getQName(i),attr.getValue(i)));
			data.put(attr.getQName(i),attr.getValue(i));
		}
	}
	
	@Override
	public void endElement(String uri, String localName, String name)
			throws SAXException {
		mCurrentTAG = null;
	}
	
	@Override
	public void characters(char ch[], int start, int length) {
		String curStr = new String(ch,start,length);
		if(mCurrentTAG == null){
			return;
		}
		if(data.containsKey(mCurrentTAG)){
			curStr = (String)data.get(mCurrentTAG)+curStr;
		}
		data.put(mCurrentTAG, curStr.trim());
	}
}